<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <div class="content">
          <div class="topTitle">线索信息</div>
          <NSpace>
            <NForm ref="formRef" :model="formValue" :rules="rules" require-mark-placement="left" label-placement="left" :label-width="115"
              label-align="right">
              <NSpace>
                <NFormItem label="线索名称:" path="clueName">
                  <NInput v-model:value="formValue.clueName" placeholder="输入线索名称" style="width: 350px"/>
                </NFormItem>
                <NFormItem label="征集信息:" path="collectorId">
                  <NSelect :options="listOption" v-model:value="formValue.collectorId" placeholder="请选择藏家" clearable
                    @update-value="queryListOption" style="width: 155px;" filterable/>
                </NFormItem>
                <NFormItem label=" " path="provideId" :label-width="10">
                  <NSelect :options="listCOption" v-model:value="formValue.provideId" placeholder="请选择征集信息" 
                     style="width: 200px;"  filterable multiple @update-value="changeSS" />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="移交人:" path="transferUser">
                  <NInput v-model:value="formValue.transferUser" placeholder="输入移交人" style="width: 350px" />
                </NFormItem>
                <NFormItem label="接收人:" path="receiveUser">
                  <NInput v-model:value="formValue.receiveUser" placeholder="输入接收人" style="width: 380px" />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="接收时间:" path="receiveTime">
                 <NDatePicker input-readonly v-model:formatted-value="datetime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"  default-time="00:00:00"
                    style="width: 350px" placeholder="输入接收时间" />
                </NFormItem>
              </NSpace>
            </NForm>
          </NSpace>
          <div class="topTitle">征集信息</div>
          <NSpace>
            <NForm ref="formRef2" :model="formValue2" require-mark-placement="left" :rules="rules2" label-placement="left" :label-width="115"
              label-align="right" :disabled="formValue.provideId ? true : false">
              <NSpace>
                <NFormItem label="姓名:" path="userName">
                  <NInput clearable v-model:value="formValue2.userName" placeholder="输入姓名" style="width: 350px"
                    @update-value="change1" @blur="handleBlur" @clear="userNameClear"/>
                  <table class="tableT" v-if="listNameShow">
                    <tbody>
                      <tr v-for="(item, i) in listName" :key="i" class="tr" @click="trClick">
                        <td class="td">{{ item }}</td>
                      </tr>
                    </tbody>
                  </table>

                </NFormItem>
                <NFormItem label="单位:" path="dept">
                  <NInput v-model:value="formValue2.dept" placeholder="输入单位" style="width: 380px"
                    @update-value="change2" />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="联系方式:" path="phone">
                  <NInput v-model:value="formValue2.phone" placeholder="输入联系方式" style="width: 350px"
                    @update-value="change3" />
                </NFormItem>
                <NFormItem label="提交时间:" path="commitTime">
                 <NDatePicker input-readonly v-model:formatted-value="datetimeT" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"  default-time="00:00:00"
                    style="width: 380px" placeholder="输入提交时间" />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="证件类型:" path="idType">
                  <NSelect :options="listZOption" v-model:value="formValue2.idType" placeholder="请选择证件类型" clearable
                    style="width: 350px" @update-value="change4" />
                </NFormItem>
                <NFormItem label="证件号:" path="idNo">
                  <NInput v-model:value="formValue2.idNo" placeholder="输入证件号" style="width: 380px"
                    @update-value="change5" />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="行政区划:" path="regionCode">
                  <NSelect :options="listXZOption" v-model:value="formValue3.regionCode1" placeholder="请选择行政区划" clearable
                    style="width: 170px;margin-right: 10px;"  label-field="shortName" value-field="regionCode" @update-value="change6" :disabled="formValue.collectorId ? true : false"/>
                    <NSelect :options="listXZOption2" v-model:value="formValue3.regionCode" placeholder="请选择行政区划" clearable
                    style="width: 170px"  label-field="shortName" value-field="regionCode" :disabled="isAbled||(formValue.collectorId ? true : false)"/>
                </NFormItem>
              </NSpace>
            </NForm>
          </NSpace>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton style="width: 78px" ghost @click="goBack">
        取消
      </NButton>
      <NButton type="primary" style="width: 78px" @click="confirm" :disabled="loading" :loading="loading">
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  useMessage,
  NDatePicker
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { keysOf } from '@/utils/object'
import type { HttpResponse } from '@/utils/http'
import { format } from 'date-fns'
import { useRoute } from 'vue-router'
import useRouteReplace from '@/hooks/useRouteReplace'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const isAbled=ref(false)
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const formRef2 = ref<FormInst | null>(null)
const listOption = ref([])
const listZOption = ref([])
const listXZOption=ref([])
const listXZOption2=ref([])
const listNameOption = ref<any>([])
const formValue3=reactive({
  regionCode1:null,
  regionCode:null
})
const formValue2 = reactive({
  userName: null,
  dept: null,
  phone: null,
  commitTime: null,
  idNo: null,
  idType: null
})
const formValue = reactive({
  clueName: null,
  provideId: null,
  collectorId:null,
  transferUser: null,
  receiveUser: null,
  receiveTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
  regionCode:null,
  regionName:null
})
const form = {
  collector: {
    dept: formValue2.dept,
    idNo: formValue2.idNo,
    idType: formValue2.idType,
    phone: formValue2.phone,
    userName: formValue2.userName
  }
}
const rules = ref({
  clueName: {
    required: true,
    message: '请输入线索名称',
    trigger: ['change', 'blur']
  },
  transferUser: {
    required: true,
    message: '请输入移交人',
    trigger: ['change', 'blur']
  },
  receiveUser: {
    required: true,
    message: '请输入接收人',
    trigger: ['change', 'blur']
  },
  receiveTime:{
    required: true,
    message: '请选择接收时间',
    trigger: ['change', 'blur']
  },
  provideId:{
    required: false,
    trigger: ['change', 'blur'],
    validator: (_:any,value:any) => {
      if(formValue.collectorId){
        if (!value) return new Error('请选择征集信息')
      return true
      }else{
        return true
      }
    }
  }
})
const rules2 = {
  userName: {
    required: true,
    message: '请输入姓名',
    trigger: ['change', 'blur','input']
  }
}
const datetime = computed<any>({
  get() {
    return formValue.receiveTime
  },
  set(v) {
    formValue.receiveTime = v
  }
})
const datetimeT = computed<any>({
  get() {
    return formValue2.commitTime
  },
  set(v) {
    formValue2.commitTime = v
  }
})
// 返回
const goBack = () => {
  // const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  
    // tags.splice(index, 1)
if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else routeReplace()
}
//征集信息-藏家下拉
const getFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listCollectorOptions'
  })
  if (error) return message.error(error.message)
  listOption.value = res.data
}
const listCOption=ref([])
//征集品下拉
const getCFunction = async (collectorId:any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listProvideOptionsByCollectorId',
    override:{
      params:{
        collectorId
      }
    }
  })
  if (error) return message.error(error.message)
  listCOption.value = res.data
}
const listU = ref<any>([])
//藏家姓名下拉 
const getNameFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'controller',
    api: 'listOptions'
  })
  if (error) return message.error(error.message)
  listNameOption.value = res.data.map((e: any) => e.userName)
  listU.value = res.data
}
//证件类型下拉
const getZFunction = async () => {
  listZOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A37'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listZOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
//行政区域下拉
const getXZFunction = async (v:any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'parentCode',
    uri:{
      parentCode:v
    }
  })
  if (error) return message.error(error.message)
  listXZOption.value=res.data
}
const getXZFunction2 = async (v:any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'parentCode',
    uri:{
      parentCode:v
    }
  })
  if (error) return message.error(error.message)
  listXZOption2.value=res.data
if(res.data.length===1){
  isAbled.value=true
}else{
  isAbled.value=false
}
}

const queryListOption = (v: any) => {
  formValue.provideId=null
  if(v){
    getInfo(v)
  }
  getCFunction(v)
}
const changeSS=(v:any)=>{
  formValue.provideId=v
}

const getInfo = async (v: any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'infoProvideByCollectorId',
    override: {
      params: {
        id: v
      }
    }
  })
  if (error) return message.error(error.message)
  if(res.data.provideVo){
    keysOf(res.data.provideVo).forEach((e) => {
    // @ts-ignore
    formValue2[e] = res.data.provideVo[e]
  })
  }else{
      formValue2.userName = null
      formValue2.dept = null
      formValue2.phone = null
      formValue2.commitTime = null
      formValue2.idType = null
      formValue2.idNo = null
  }
}
//新增
const confirm = async () => {
  const validate = await Promise.all([
    new Promise((resolve, reject) => {
      formRef.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])
  const validate2 = await Promise.all([
    new Promise((resolve, reject) => {
      formRef2.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])
  if (!validate.every(Boolean) || !validate2.every(Boolean)) return
  loading.value = true
  if(formValue.provideId){
    // @ts-ignore
    formValue.provideId=formValue.provideId.join(',')
  }
  if(isAbled.value){
    formValue.regionCode=formValue3.regionCode1
    console.log(formValue)
  // @ts-ignore
  formValue.regionName=listXZOption.value.filter((v)=>v.regionCode===formValue3.regionCode1)[0].shortName
  }else{
    formValue.regionCode=formValue3.regionCode
   if(formValue3.regionCode){
// @ts-ignore
formValue.regionName=listXZOption2.value.filter((v)=>v.regionCode===formValue3.regionCode)[0].shortName
   }
  }
  
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'save',
    override: {
      data: {
        ...form,
        ...formValue,
        ...formValue2
      }
    }
  })
  loading.value = false
  if (error) return message.error(error.message)
  message.success(res.msg)
  goBack()
}
const listNameShow = ref(false)
const trClick = (v: any) => {
  formValue2.userName = v.target.innerText
  aList.value = listU.value.filter((e: any) => v.target.innerText === e.userName)[0]
  console.log(aList.value)
  if (aList.value) {
    form.collector.dept = aList.value.dept
    form.collector.phone = aList.value.phone
    form.collector.idType = aList.value.idType
    form.collector.idNo = aList.value.idNo
    form.collector.userName = aList.value.userName
    formValue2.dept = aList.value.dept
    formValue2.phone = aList.value.phone
    formValue2.idType = aList.value.idType
    formValue2.idNo = aList.value.idNo
    formValue2.userName = aList.value.userName
  }
  listNameShow.value = false
}
const listName = ref([])
const aList = ref<any>([])
const change1 = (v: any) => {
  listName.value = listNameOption.value.filter((t: any) => {
    return t.includes(v)
  })
  listNameShow.value = true
  formValue2.userName = v
  form.collector.userName = v
}
const handleBlur=()=>{
  setTimeout(() => {
  listNameShow.value = false
  }, 500);
}
const userNameClear=()=>{
  formValue2.userName = null
      formValue2.dept = null
      formValue2.phone = null
      formValue2.commitTime = null
      formValue2.idType = null
      formValue2.idNo = null
      form.collector.dept = null
      form.collector.idNo = null
      form.collector.idType = null
      form.collector.phone = null
      form.collector.userName = null
}
const change2 = (v: any) => {
  form.collector.dept = v
}
const change3 = (v: any) => {
  form.collector.phone = v
}
const change4 = (v: any) => {
  form.collector.idType = v
}
const change5 = (v: any) => {
  form.collector.idNo = v
}
const change6=(v:any)=>{
  formValue3.regionCode=null,
  getXZFunction2(v)
}
watch(() => formValue2.userName, () => {
  if (!formValue2.userName) {
    listName.value = []
  }
})
watch(
  () => formValue.collectorId,
  () => {
    if (!formValue.collectorId) {
      formValue2.userName = null
      formValue2.dept = null
      formValue2.phone = null
      formValue2.commitTime = null
      formValue2.idType = null
      formValue2.idNo = null
      rules.value.provideId.required=false
    } else {
      form.collector.dept = null
      form.collector.idNo = null
      form.collector.idType = null
      form.collector.phone = null
      form.collector.userName = null
      rules.value.provideId.required=true
    }
  }
)
onMounted(() => {
  getFunction()
  getNameFunction()
  getZFunction()
  getXZFunction(100000000000)

})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .tableT {
        position: absolute;
        top: 38px;
        z-index: 888;
        background-color: #fff;
        width: 350px;

        .tr {
          height: 30px;
          margin: 0 10px;
          cursor: pointer;
          &:hover{
            background-color: #ebeceb;
          }

          .td {
            padding: 0 10px;
          }
        }
      }

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-base-selection-tags) {
flex-wrap: nowrap;
overflow: hidden;
.n-base-clear{
  display: none;
}
}

</style>
